using System;
using System.Collections.Generic;
using NHibernate.Mapping.Attributes;
using NHMA = NHibernate.Mapping.Attributes;

namespace SuperMarketManagement.Entity
{

    [Class(Name = "Product")]
    public class Product
    {
        [Id(1, Name = "AutoId"), Generator(2, Class = "native")]
        public virtual long AutoId { get; set; }

        [ManyToOne(Column = "categoryAutoId")]
        public virtual Category Category { get; set; }
        [Property]
        public virtual string Name { get; set; }
        [Property]
        public virtual string Code { get; set; }
        [Property]
        public virtual string Producer { get; set; }
        [Property]
        public virtual string Description { get; set; }
        [Property]
        public virtual string Unit { get; set; }
        [Property]
        public virtual double CurrentSellingPrice { get; set; }


        [NHMA.List(1, Cascade = "all-delete-orphan")]
        [NHMA.Key(2, Column = "ProductAutoId")]
        [NHMA.Index(3, Column = "BlockIndex")]
        [NHMA.OneToMany(4, ClassType = typeof(ProductBlock))]
        public virtual IList<ProductBlock> Blocks { get; set; }

        [NHMA.List(1, Cascade = "all-delete-orphan")]
        [NHMA.Key(2, Column = "ProductAutoId")]
        [NHMA.Index(3, Column = "ShrinkageIndex")]
        [NHMA.OneToMany(4, ClassType = typeof(Shrinkage))]
        public virtual IList<Shrinkage> Shrinkages { get; set; }

        public Product()
        {
            Blocks = new List<ProductBlock>();
            Shrinkages = new List<Shrinkage>();
        }

        public Product(String name, String code, String producer, String description, String unit, long currentSellingPrice, Category category, params ProductBlock[] blocks)
            : this()
        {
            Name = name;
            Code = code;
            Producer = producer;
            Description = description;
            Unit = unit;
            CurrentSellingPrice = currentSellingPrice;
            Category = category;
            foreach (ProductBlock b in blocks)
            {
                AddBlock(b);
            }
        }

        public virtual void AddBlock(ProductBlock b)
        {
            Blocks.Add(b);
            b.Product = this;
        }

        public virtual void AddShrinkage(Shrinkage shrinkage)
        {
            Shrinkages.Add(shrinkage);
            shrinkage.Product = this;
        }

        public virtual double GetTotalAvailable()
        {
            double sum = 0;
            foreach (ProductBlock block in Blocks)
            {
                sum += block.AvailableUnits;
            }
            return sum;
        }
    }
}